// index.js
const dataType = require('../../data/data.js')
const db = wx.cloud.database()
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    startTime: '',
    startBaba: '',
    state: app.globalData.state,//0表示没开始拉粑粑，1表示正在拉粑粑，2表示结束拉粑粑
    displayTime: '00分00秒',
    minutes: 0,
    seconds: 0,
    totalTime: 0,
    timer: '',
  },

  init() {
    this.setData({
      startTime: '',
      displayTime: '00分00秒',
      minutes: 0,
      seconds: 0,
      totalTime: 0,
      timer: '',
      weekDay: ''
    })
  },

  startBaBa() {
    const startTime = new Date().getTime()
    let date = new Date(startTime);
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hour = date.getHours();
    let minute = date.getMinutes();
    let second = date.getSeconds();
    month = month < 10 ? "0" + month : month;
    day = day < 10 ? "0" + day : day;
    hour = hour < 10 ? "0" + hour : hour;
    minute = minute < 10 ? "0" + minute : minute;
    second = second < 10 ? "0" + second : second;

    const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    const weekday = date.getDay();

    this.data.timer = setInterval(() => {
      let second = this.data.seconds + 1;
      let minute = this.data.minutes
      if (second >= 60) {
        minute++
        second = 0
      }
      let displayTime = `${minute.toString().padStart(2, '0')}分${second.toString().padStart(2, '0')}秒`;
      this.setData({
        minutes: minute,
        seconds: second,
        displayTime: displayTime,
        weekDay: weekDays[weekday]
      });
    }, 1000)

    app.globalData.state = 1
    this.setData({
      state: app.globalData.state,
      startTime: `${year}-${month}-${day} ${hour}:${minute}:${second}`,
      startBaba: startTime
    })
  },

  stopTime() {
    wx.showModal({
      title: '提示',
      content: '结束拉粑粑？',
      confirmColor: 'red',
      complete: (res) => {
        if (res.confirm) {
          clearInterval(this.data.timer)
          const totalBaba = this.data.minutes * 60 + this.data.seconds
          wx.navigateTo({
            url: `/pages/saveBabaPage/saveBabaPage?startTime=${this.data.startTime}&displayTime=${this.data.displayTime}&totalBaba=${totalBaba}&weekDay=${this.data.weekDay}`,
          })
          this.init()

        }
      }
    })
  },

  async inquireDatabase() {
    const res = await wx.cloud.callFunction({
      name: 'inquireDatabase',
    })
    return res.result
  },

  async getOpenId(){
   try{
    const res = await wx.cloud.callFunction({
      name: 'inquireUserInfo'
    })
    console.log('请求openid成功',res.result.openid)
    try{
      const openid=wx.getStorageSync('openid')
      if (openid !== res.result.openid) {
        wx.setStorage({
          key: 'openid',
          data: res.result.openid,
          success: () => {
            console.log('openid保存缓存成功',res.result.openid);
          },
          fail: (e) => {
            console.error('openid保存缓存失败', e);
          }
        })
      }
    }catch(e){
      console.error('openid保存缓存失败')
    }
   }catch(e){
    console.error('请求openid失败')
   }
  },

  async updateUserInfo() {
    try {
      const getUserInfo = await db.collection('user').get()
      console.log(getUserInfo)
      const userInfoCache = wx.getStorageSync('userInfoResult')
      if (!userInfoCache || JSON.stringify(userInfoCache) !== JSON.stringify(getUserInfo)) {
        wx.setStorage({
          key: 'userInfoResult',
          data: getUserInfo
        })
      }
    } catch (e) {
      console.error('数据库查询失败:', e);
      wx.showToast({
        title: '数据加载失败',
        icon: 'none'
      });
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad() {
    try {
      const result = await this.inquireDatabase()
      console.log(result)
      const cacheResult = wx.getStorageSync('dataBaseResult');
      if (!cacheResult || JSON.stringify(cacheResult) !== JSON.stringify(result)) {
        wx.setStorage({
          key: 'dataBaseResult',
          data: result
        })
      }
    } catch (e) {
      console.error('数据库查询失败:', e);
      wx.showToast({
        title: '数据加载失败',
        icon: 'none'
      });
    }
    this.updateUserInfo()
    this.getOpenId()
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      state: app.globalData.state
    })
  },

  findToilet() {
    wx.navigateTo({
      url: '/pages/findToiletPage/findToiletPage',
    })
  },

  aiAnswerQuestion() {
    wx.navigateTo({
      url: '/pages/aiAnswerPage/aiAnswerPage',
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
